package com.example.rocketmq.demo.producer;

import com.example.rocketmq.demo.config.RocketMQConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 批量消息生产者
 */
@Slf4j
@Component
public class BatchProducer {

    @Autowired
    @Qualifier("defaultMQProducer")
    private DefaultMQProducer producer;

    // 批量消息大小限制，默认为4MB
    private static final int MAX_MESSAGE_SIZE = 4 * 1024 * 1024;

    /**
     * 发送批量消息
     *
     * @param contentList 消息内容列表
     * @return 发送结果
     */
    public SendResult sendBatch(List<String> contentList) throws Exception {
        List<Message> messageList = new ArrayList<>();

        for (String content : contentList) {
            Message message = new Message(
                    RocketMQConstant.TOPIC_BATCH,
                    RocketMQConstant.TAG_BATCH,
                    content.getBytes(StandardCharsets.UTF_8)
            );
            messageList.add(message);
        }

        // 检查批量消息大小
        if (isBatchOK(messageList)) {
            SendResult sendResult = producer.send(messageList);
            log.info("批量消息发送结果: {}, 消息数量: {}", sendResult, messageList.size());
            return sendResult;
        } else {
            log.error("批量消息大小超过限制: {} bytes", MAX_MESSAGE_SIZE);
            throw new Exception("批量消息大小超过限制");
        }
    }

    /**
     * 检查批量消息是否超过大小限制
     *
     * @param messages 消息列表
     * @return 是否符合大小限制
     */
    private boolean isBatchOK(List<Message> messages) {
        int totalSize = 0;
        for (Message message : messages) {
            totalSize += message.getBody().length;
            // 批量消息的每条消息不得超过1MB
            if (message.getBody().length > 1024 * 1024) {
                return false;
            }
        }
        return totalSize <= MAX_MESSAGE_SIZE;
    }
}
